﻿using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using QuailDashboard.View.Data;
using QuailDashboard.View.Views;

namespace QuailDashboard.View
{
    public partial class App : Application
    {
        public App()
        {
            Startup += Application_Startup;
            Exit += Application_Exit;
            UnhandledException += Application_UnhandledException;

            InitializeComponent();
        }

        /// <summary>
        /// Gets the "Application.Current" instance as an App instance
        /// </summary>
        public static App CurrentApp
        {
            get
            {
                return Current as App;
            }
        }

        /// <summary>
        /// Gets or sets the default service endpoint address
        /// </summary>
        public string DefaultServiceEndpointAddress
        {
            get; set;
        }


        /// <summary>
        /// Gets or sets the TestRunner service endpoint address
        /// </summary>
        public string TestRunnerServiceEndpointAddress
        {
            get;
            set;
        }


        /// <summary>
        /// Gets the users client machine address
        /// </summary>
        public string UserClientAddress
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the user's name
        /// </summary>
        public string UserName
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets or sets a value indicating whether to enable test execution
        /// </summary>
        public bool EnableTestExecute
        {
            get;
            set;
        }

        /// <summary>
        /// Gets the user preferences
        /// </summary>
        public UserPreferencesData UserPreferences
        {
            get;
            private set;
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            RootVisual = new MainPage();
            GetUserPreferences();

            DefaultServiceEndpointAddress = e.InitParams["QuailDataServiceAddress"];
            TestRunnerServiceEndpointAddress = e.InitParams["TestRunnerServiceAddress"];
            UserClientAddress = e.InitParams["txtUserIP"];
            UserName = e.InitParams["User.Identity.Name"];
            EnableTestExecute = string.Compare(e.InitParams["EnableTestExecute"], "true", StringComparison.CurrentCultureIgnoreCase) == 0;
        }

        private void Application_Exit(object sender, EventArgs e)
        {
            SaveUserPreferences();
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // a ChildWindow control.
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                ChildWindow errorWin = new ErrorWindow(e.ExceptionObject);
                errorWin.Show();
            }
        }

        // Reading from Isolated Storage
        private void GetUserPreferences()
        {
            try
            {
                UserPreferencesData preferencesData;
                IsolatedStorageSettings.ApplicationSettings.TryGetValue("UserPreferences", out preferencesData);

                if (preferencesData == null)
                    preferencesData = new UserPreferencesData();

                UserPreferences = preferencesData;
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Unable to access user preferences from Isolated Storage - {0}", ex.Message));
            }
        }

        // Saving to Isolated Storage
        private void SaveUserPreferences()
        {
            try
            {
                IsolatedStorageSettings.ApplicationSettings["UserPreferences"] = UserPreferences;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Unable to save user preferences to Isolated Storage - {0}", ex.Message));
            }
        }

        /// <summary>
        /// Shows a popup window with the exception information
        /// </summary>
        /// <param name="e">The exception</param>
        public void ShowError(Exception e)
        {
            ChildWindow errorWin = new ErrorWindow(e);
            errorWin.Show();
        }

        /// <summary>
        /// Shows a popup window with the exception information and a custom message.
        /// </summary>
        /// <param name="message">the custom message</param>
        /// <param name="e">the exception</param>
        public void ShowError(string message, Exception e)
        {
            ChildWindow errorWin = new ErrorWindow(message, e);
            errorWin.Show();
        }
    }
}